# 1. 关于转义字符
# \ 用来表示转义字符
# \\ 表示 \的本身
# \n    换行
# \r    回车 
# \t
# windows 下面 敲一个回车  =  \r\n
# fileName = 'd:\\1.txt'
# print(fileName)


# 2. 编码问题
# ASCII  英文           # 占1个字节 
# 中文保存到二进制文件
# utf-8       unicode编码       # 中  占3个字节
# gbk gb2312  国标码            #     占2个字节 
# big5   
# 

# f = open("d:\\test1.txt","r",encoding="utf-8")     
# str = f.read()
# print(str)
# f.close()

# f = open("d:\\test2.txt","r",encoding='gb2312')     
# str = f.read()
# print(str)
# f.close()


# 3. with as 自动资源管理

# with  打开文件  as  文件对象:
#      对文件进行读写
# 运行完这段代码 自动关闭文件

# with open("d:\\test2.txt","r",encoding='gb2312') as f:    
#     str = f.read()
#     print(str)


# 4. 文件的定位

# f = open("d:\\1.txt","r")

# print(f.readline())
# print(f"位置:{f.tell()}")
# print(f.readline())
# print(f"位置:{f.tell()}")
# f.seek(6)     
# f.seek(6,0)   # 0 以文件开头为起始点
# f.seek(2,1)     # 1 当前读写位置为起始点 ???
# print(f.readline())
# print(f"位置:{f.tell()}")

# f.close()


# 5. CSV 表格数据写入
# stus = [['1001','张三','18'],['1002','里斯','19']]
# f = open("d:\\stus.csv","w")
# for stu in stus:
#     f.write(",".join(stu)+"\n")
# f.close()

# 6. 使用csv模块 
# 处理csv标准库

# 6.1 读取
# import csv
# with open("d:\\stus.csv","r") as f:
#     ls = csv.reader(f)
#     for row in ls:
#         print(row)

# 6.2 写入
# 二维表 列表方式
# import csv
# stus = [['1001','张三','18'],['1002','里斯','19']]
# with open("d:\\stus2.csv","w",newline="") as f:
#     writer = csv.writer(f,dialect="excel")
#     writer.writerow(stus)

import csv
headers = ["学号","姓名","年龄"]
stus = [{'学号':'1001','姓名':'张三','年龄':'18'},{'学号':'1002','姓名':'李四','年龄':'18'}]
with open("d:\\stus3.csv","w",newline="") as f:
    writer = csv.DictWriter(f,headers)
    writer.writerows(stus)






